package com.baidu.ueditor.tools;

import com.baidu.ueditor.UEditorConfig;
import com.baidu.ueditor.entity.FileEntity;

import java.io.File;
import java.sql.*;

public class SqliteUtils {

    public static String url = null;

    static {
        init();
    }

    private static void init() {
        try {
            String db_path = UEditorConfig.getGLOBAL_SAVE_PATH_PREFFIX() + "/ueditor/db";
            File file = new File(db_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(db_path + "/sqlite.db");
            Class.forName("org.sqlite.JDBC");
            url = "jdbc:sqlite:" + db_path + "/sqlite.db";
            if (file.exists()) {
                return;
            }

          /*  //建立一个数据库名sqlite.db的连接，如果不存在就在当前目录下创建之
            Connection conn = DriverManager.getConnection(url);
            Statement statement = conn.createStatement();

            //建表语句
            conn.close();*/
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }

    public static void createTableIfNotExists(String tableName) {
        Statement statement = null;
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);

            String sql = "SELECT COUNT(*) as result_count FROM sqlite_master where type='table' and name='" + tableName + "'";
            statement = conn.createStatement();


            ResultSet rs = statement.executeQuery(sql);
            if (rs.next() && !rs.getBoolean("result_count")) {
                createTable(tableName, conn);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(statement, conn);
        }
    }

    public static void createTable(String tableName, Connection conn) {
        String sql = "CREATE TABLE \"" + tableName + "\" (\n" +
                "\"id\"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
                "\"save_name\"  TEXT NOT NULL,\n" +
                "\"upload_name\"  TEXT NOT NULL\n" +
                ")";

        String index_sql = "CREATE UNIQUE INDEX \"unique_idx\"\n" +
                "ON \"" + tableName + "\" (\"save_name\" ASC)";
        Statement statement = null;
        try {
            statement = conn.createStatement();
            statement.execute(sql);
            statement.execute(index_sql);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(statement);
        }
    }

    public static void insert(FileEntity entity, String tableName) {
        String sql = "insert into '" + tableName + "' (save_name,upload_name) " +
                "values('" + entity.getSaveName() + "','" + entity.getUploadName() + "')";
        Statement statement = null;
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
            createTableIfNotExists(tableName);
            statement = conn.createStatement();
            statement.execute(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(statement, conn);
        }
    }

    public static FileEntity getOne(String tableName, String saveName) {
        String sql = "select * from '" + tableName + "' where save_name='" + saveName + "'";
        Statement statement = null;
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url);
            statement = conn.createStatement();

            ResultSet rs = statement.executeQuery(sql);

            FileEntity entity = null;
            if (rs.next()) {
                String uploadName = rs.getString("upload_name");
                entity = new FileEntity(saveName, uploadName);
            }
            return entity;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(statement, conn);
        }
    }

    private static void close(AutoCloseable... closeables) {
        if (closeables == null || closeables.length == 0) {
            return;
        }
        for (AutoCloseable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
